package com.eastdigit.shiro.realm;

import com.eastdigit.shiro.ShiroConstants;
import com.eastdigit.shiro.authc.HmacSHA256Utils;
import com.eastdigit.shiro.authc.IncorrectCaptchaException;
import com.eastdigit.shiro.authc.StateToken;
import com.eastdigit.shiro.authc.StatelessToken;
import com.eastdigit.system.model.Constants;
import com.eastdigit.system.model.IUser;
import com.eastdigit.system.model.Menu;
import com.eastdigit.system.service.ICaptchaService;
import com.eastdigit.system.service.IPermissionService;
import com.eastdigit.system.service.IUserService;
import com.eastdigit.util.StringUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by acer on 14-2-11.
 */
public class UserStateRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;
    @Autowired
    private ICaptchaService captchaService;
    @Autowired
    private IPermissionService permissionService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof StateToken || token instanceof StatelessToken;
    }

    /**
     * 
     * 当用户进行访问链接时的授权方法
     * 
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        if (principals == null) {
            throw new AuthorizationException("Principal对象不能为空");
        }

        // 用户所有响应的permission（功能点）
        List<String> permissions = new ArrayList<String>();

        String userId = (String) principals.fromRealm(getName()).iterator().next();
        List<Menu> menus = permissionService.queryPermissionsOfUser(userId);
        for (Menu menu : menus) {
            if (Constants.MENU_TYPE_FUNCTION.equals(menu.getType())) {// 功能点
                if (!StringUtil.isNull(menu.getUrl())) {
                    permissions.add(menu.getUrl());
                }
            } else {// 菜单
                if (!StringUtil.isNull(menu.getCtrlPath())) {
                    permissions.add("/js/controllers/" + menu.getCtrlPath());
                }
                if (!StringUtil.isNull(menu.getTemplateUrl())) {
                    permissions.add("/views/" + menu.getTemplateUrl());
                }
            }
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(permissions);

        return info;
    }

    /**
     * 用户登录的认证方法
     * 
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        if (authcToken instanceof StateToken) {// 有状态
            StateToken token = (StateToken) authcToken;
            String username = token.getUsername();
            if (username == null) {
                throw new AccountException("用户名不能为空");
            }
            // 增加判断验证码逻辑
            String captcha = token.getCaptcha();
            if (Constants.LOGIN_CAPTCHA && !captchaService.isValid(captcha)) {
                throw new IncorrectCaptchaException("验证码错误");
            }

            IUser user = userService.queryByCode(username);
            if (user == null) {
                throw new UnknownAccountException("用户不存在");
            }
            return new SimpleAuthenticationInfo(user.getId(), user.getPassword(), getName());
        } else {// 无状态
            StatelessToken statelessToken = (StatelessToken) authcToken;
            String serverDigest = HmacSHA256Utils.digest(ShiroConstants.KEY, statelessToken.getUserId(),
                    statelessToken.getTimestamp(), statelessToken.getNonce());
            return new SimpleAuthenticationInfo(statelessToken.getUserId(), serverDigest, getName());
        }
    }
}
